package filters;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by hadoop on 17-6-14.
 * 用来进行权限控制，注意不要拦截了css，js等资源文件，登录路径，登录表单处理路径
 * 在这里认为请求路径含有 . 作为资源文件请求，不会处理含有.的路径
 * 设置只要请求的路径以.jsp结尾都会提交到登录界面，所以登录界面路径不能以.jsp结尾，否则会死循环
 */
@WebFilter(filterName = "AuthorityFilter",urlPatterns = {"/*"}, asyncSupported = true,
initParams = {
        @WebInitParam(name = "encoding",value = "utf-8"),
        @WebInitParam(name = "loginPage", value = "/login"),
        @WebInitParam(name = "LoginServlet",value = "/LoginServlet")
})
public class AuthorityFilter implements Filter{
    private FilterConfig config;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.config = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        String encoding = this.config.getInitParameter("encoding");
        String loginPage = this.config.getInitParameter("loginPage");
        String LoginServlet = this.config.getInitParameter("LoginServlet");

        HttpServletRequest request = (HttpServletRequest)servletRequest;
        request.setCharacterEncoding(encoding);
        HttpSession session = request.getSession();
        String reqPath = request.getServletPath();


        if(session.getAttribute("username") == null
                && !reqPath.endsWith(loginPage)
                && !reqPath.endsWith(LoginServlet)
                && !reqPath.contains(".")
                || reqPath.endsWith(".jsp")){
            request.setAttribute("errMsg","请先登录");
            request.getRequestDispatcher(loginPage).forward(servletRequest,servletResponse);
        }else{
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

    @Override
    public void destroy() {
        this.config = null;
    }
}
